package model.webService;

import java.net.Socket;
import java.net.SocketException;

import android.util.Log;
import view.ArgusActivity;

public class ClientThread implements Runnable 
{
	private static final String TAG = ClientThread.class.getSimpleName();

	private ArgusActivity _activity;
	
	private Socket connectionSocket;	
	private CallReceiver callReceiver;
	
	public ClientThread(ArgusActivity activity)
	{
		_activity = activity;
	}
	
	@Override
	public void run() 
	{
		connectionSocket = SocketConnector.createConnection();
		
		callReceiver = new CallReceiver(connectionSocket, _activity);
		
		try {
			sendSocketCall(Command.Login);
		} catch (SocketException e) {
			Log.e(TAG, e.toString());
		}
		
		callReceiver.listen();
	}

	/**
	 * Sends a call to the web service.
	 * @param command The command that indicates the purpose of the call.
	 */
	private void sendSocketCall(Command command) throws SocketException 
	{
		sendSocketCall("", command);
	}

	public void deleteSocket() 
	{
		connectionSocket = null;		
	}

	public void handleLostConnection() 
	{
		callReceiver.handleLostConnection();
	}

	/**
	 * Sends a call to the web service.
	 * @param msg The message to send along with the call.
	 * @param command The command to indicate the purpose of the call.
	 */
	public void sendSocketCall(String msg, Command command) throws SocketException 
	{
		CallSender.sendSocketCall(connectionSocket, msg, command);
		
		if(command != Command.Login)
			callReceiver.setLastCommand(command);
	}

	public void setActivity(ArgusActivity observer) 
	{
		_activity = observer;
		callReceiver.setActivity(_activity);
	}

}
